const fs = require("fs");
const path = require("path");
const tinify = require("tinify");
let list = process.argv;
console.log('list', list[2])
tinify.key = "41qYRVZY3Zd0Cfm1P22zYw2bDMdJvPXb";
let compressionsThisMonth = tinify.compressionCount;

// function compressAll() {
//     if (pathList.length > 0) {
//         for (let img of pathList) {
//             console.log(path.basename(img));
//             compress(img);
//         }
//     } else {
//         console.log('没有需要压缩的图片。')
//     }
// }

function tinypngCompress(filePath, callback) {
    const source = tinify.fromFile(filePath);
    source.toFile(filePath, function (err) {
        if (err) {
            if (err instanceof tinify.AccountError) {
                console.error("当前账户请求已达到限制");
            } else if (err instanceof tinify.ClientError) {
                console.error("文件数据异常，请检查是否是图片文件");
            } else if (err instanceof tinify.ServerError) {
                console.error("服务器原因暂不可用，请稍后再试");
            } else if (err instanceof tinify.ConnectionError) {
                console.error("连接失败，请检查网络...");
            } else {
            }
        }
        if (callback) callback(err)
    });
}
if (list[2]) {
    let filePath = list[2];
    let beforeSize = fs.statSync(filePath).size;
    tinypngCompress(filePath, (err) => {
        let nowSize = fs.statSync(filePath).size;
        let compressEffectPercent = (beforeSize - nowSize) / beforeSize * 100;
        if (err) {
            console.log('压缩失败');
        } else {
            console.log('压缩成功', compressEffectPercent);
            console.log('次数', compressionsThisMonth);
        }
    })
}